package com.gin.kotlin.no_gay_alliance.worker

import android.content.Context
import android.util.Log
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkContinuation
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.interceptor.LoggingInterceptor
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.nga.enums.param.MissionEvent
import com.gin.nga.enums.param.MissionType
import com.gin.nga.main.NgaApi
import java.util.concurrent.TimeUnit

class AutoMissionWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        val userId = inputData.getLong(KEY_USER_ID, 0L)
        val account = App.INSTANCE.database.accountDao().getByUserId(userId)
        if (account == null) {
            Log.w(TAG, "任务失败: 账号不存在, userId = $userId")
            return Result.failure()
        }
        val username = account.username
        val api = NgaApi.Builder(account.toCookie(), GlobalProperty.getInstance().domain)
            .also { it.clientBuilder.addInterceptor(LoggingInterceptor()) }
            .build().missionApi

        try {
            val missions = api.list(MissionEvent.SIGN_IN.id, MissionType.COUNTER.toBit()).execute().body()?.data?.flatten()
            if (missions.isNullOrEmpty()) {
                val msg = "未获取到任务: $username"
                Log.w(TAG, msg)
                return Result.success()
            }
            // 逐个完成任务
            missions.filter { it.isCheckAble() == true }.forEach {
                api.check(it.id!!).execute().body()?.data?.also { m ->
                    val missionInfo = m.missionInfo
                    val name = it.name?:missionInfo?.name ?:missionInfo?.missionDetail?.name
                    val msg = "$username 任务已完成: $name"
                    Log.i(TAG, msg)
                    App.INSTANCE.handler?.toast(msg)
                }
            }
            return Result.success()
        } catch (e: Exception) {
            e.printStackTrace()
            val msg = "查询任务失败: ${e.localizedMessage}"
            Log.w(TAG, msg)
            App.INSTANCE.handler?.toast(msg)
            return Result.failure()
        }
    }

    companion object {
        private const val KEY_USER_ID = "user_id"
        private val TAG = AutoMissionWorker::class.java.simpleName

        @JvmStatic
        fun buildRequest(userId: Long) = OneTimeWorkRequest.Builder(AutoMissionWorker::class.java)
            // 执行参数
            .setInputData(Data.Builder().putLong(KEY_USER_ID, userId).build())
            // 任务限制：必须联网
            .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
            // 重试策略
            .setBackoffCriteria(BackoffPolicy.LINEAR, WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
            .build()

        /**
         * 开始一个系列任务
         * @param userId List<Long>
         */
        @JvmStatic
        fun start(userId: List<Long>) {
            if (userId.isEmpty()) return
            val manager = WorkManager.getInstance(App.INSTANCE)
            var workContinuation: WorkContinuation? = null
            val requests = userId.map { buildRequest(it) }

            requests.forEach {
                workContinuation = if (workContinuation == null)
                    manager.beginWith(it)
                else
                    workContinuation!!.then(it)
            }
            workContinuation!!.enqueue()
        }

        /**
         * 对所有开关开启的账号执行签到
         */
        @JvmStatic
        fun start() {
            App.INSTANCE.database.accountDao().list().filter { it.autoMission }.map { it.userId }.takeIf { it.isNotEmpty() }?.also { start(it) }
        }

    }
}